package com.csdj.config;

import com.csdj.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 涵哥
 * @date 2023-09-01 10:09
 *  shiro框架的验证方式
 */
@Configuration
public class ShiroConfig {

    @Autowired
    private MyRealm myRealm;

    /**
     * 配置安全管理器
     * @return
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        // 安全管理器
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 把realm 放进去
        defaultWebSecurityManager.setRealm(myRealm);
      /*  // 如果使用了md5加密了的话就
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 散列次数
        hashedCredentialsMatcher.setHashIterations();
        // 加密方式
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);*/
        return defaultWebSecurityManager;
    }


    /**
     * 过滤器链
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        // 创建一个ShiroFilterFactoryBean对象，用于创建ShiroFilter
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置SecurityManager，用于管理Subject的认证、授权等功能
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 创建一个Map对象，用于存放URL和过滤器的映射关系
        Map<String,String> map = new LinkedHashMap<>();
        // 设置不需要认证的静态资源，使用anon过滤器
        map.put("/css/**","anon");
        map.put("/docs/**","anon");
        map.put("/images/**","anon");
        map.put("/js/**","anon");
        map.put("/My97DatePicker/**","anon");
        // 设置不需要认证的登录相关请求，使用anon过滤器
        map.put("/login.html","anon");
        map.put("/autoWater/login","anon");
        map.put("/autoWater/logout","anon");
        // 设置需要认证的页面请求，使用authc过滤器
        map.put("/page/**","authc");
        // 设置其他所有请求都需要认证，使用authc过滤器
        map.put("/**","authc");
        // 将Map对象设置到ShiroFilterFactoryBean中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 设置登录、成功和未授权的URL
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setSuccessUrl("/page/success.html");
        shiroFilterFactoryBean.setUnauthorizedUrl("/error.html");

        return shiroFilterFactoryBean;
    }
}
